import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Tabs, Tree, Button } from 'antd';
import styles from './index.less';
const { TabPane } = Tabs;
import CreateRoleModel from './createRole';
import { forEach, find, cloneDeep } from 'lodash';
/**
 * 用户角色管理界面
 * @param props
 * @returns
 */
const Role = (props: any) => {
  const { dispatch, loading, accessData } = props;

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [roleData, setRoleData] = useState([]);

  const [selectRoleData, setSelectRoleData] = useState({});

  const [createEdit, setCreateEdit] = useState(false);

  const fetchRole = () => {
    dispatch({ type: 'enoadRBAC/fetchRolesData', payload: {} }).then((res) => {
      if (res && res.length > 0 && !selectRoleData._id) {
        let parent = res[0];
        setSelectRoleData(parent);
        let access = parent.access;
        access = access ? JSON.parse(access) : [];
        setCheckedKeys(access);
      }
      setRoleData(res);
    });
  };

  //拿到所有实体权限信息，展开使用。
  const deepNodeList = (
    node: { key: string; name: string; children: [] },
    nodeList: string[],
  ) => {
    if (node != null) {
      nodeList.push(node.key + '');
      forEach(
        node.children,
        (child: { key: string; name: string; children: [] }) => {
          deepNodeList(child, nodeList);
        },
      );
    }
    return nodeList;
  };

  useEffect(() => {
    fetchRole();
    dispatch({ type: 'enoadRBAC/fetchAccessData', payload: {} }).then((res) => {
      if (res) {
        //设置所有选项卡都展开.
        let keys: string[] = [];
        forEach(res, (access: { key: string; name: string; children: [] }) => {
          deepNodeList(access, keys);
        });
        setExpandedKeys(keys);
      }
    }); //获取所有权限数据。
  }, []);

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    setCheckedKeys(checkedKeysValue);
  };

  const openCreateRole = () => {
    setCreateEdit(true);
  };

  const openEditRole = () => {
    let roles = cloneDeep(selectRoleData);
    roles['access'] = JSON.stringify(checkedKeys);
    dispatch({ type: 'enoadRBAC/updateRole', payload: {...roles} }).then((res) => {
      if (res) {
        fetchRole();
      }
    }); 
    
  };

  const clickTag = (activeKey) => {
    console.log('clickTag', activeKey);
    let parent = find(roleData, (roles) => {
      return roles._id === activeKey;
    });
    if (parent) {
      setSelectRoleData(parent);
      let access = parent.access;
      access = access ? JSON.parse(access) : [];
      setCheckedKeys(access);
    }
  };

  return (
    <>
      <div className={styles.selectView}>
        <div>
          <span
            style={{
              fontSize: '16px',
              marginRight: '10px',
              fontWeight: 'bold',
            }}
          >
            {'角色权限'}
          </span>
        </div>
        <div>
          <Button
            className={styles.buttonType}
            type="primary"
            onClick={openCreateRole}
          >
            {'新建角色'}
          </Button>
        </div>
      </div>
      <div className={styles.tagSelect}>
        <Tabs tabPosition={'left'} onTabClick={clickTag}>
          {roleData &&
            roleData.map((role: { _id: string; name: string }) => {
              return (
                <TabPane tab={role.name} key={role._id}>
                  <Tree
                    style={{ maxHeight: '80vh', overflowY: 'scroll' }}
                    key={role._id}
                    checkable
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onCheck={onCheck}
                    checkedKeys={checkedKeys}
                    treeData={accessData}
                    virtual={true}
                  />
                  <Button
                    className={styles.buttonType}
                    type="primary"
                    onClick={openEditRole}
                    loading={loading.effects['enoadRBAC/updateRole']}
                  >
                    {'保存'}
                  </Button>
                </TabPane>
              );
            })}
        </Tabs>
      </div>

      {createEdit && (
        <CreateRoleModel
          createEdit={createEdit}
          setCreateEdit={setCreateEdit}
          fetchRole={fetchRole}
        />
      )}
    </>
  );
};
//关联到用户权限管理state的models中。
export default connect(({ enoadRBAC, loading }) => ({
  ...enoadRBAC,
  loading,
}))(Role);
